package com.gzu.shop.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gzu.shop.base.BaseController;
import com.gzu.shop.common.Result;
import com.gzu.shop.common.ResultStatus;
import com.gzu.shop.constant.JwtClaimsConstant;
import com.gzu.shop.constant.MessageConstant;
import com.gzu.shop.constant.RoleConst;
import com.gzu.shop.context.BaseContext;
import com.gzu.shop.dto.CategoryDTO;
import com.gzu.shop.entity.*;
import com.gzu.shop.exception.CategoryBusinessException;
import com.gzu.shop.mapper.ClassificationFirstMapper;
import com.gzu.shop.mapper.ClassificationSecondMapper;
import com.gzu.shop.mapper.ThingMapper;
import com.gzu.shop.param.SearchCondition;
import com.gzu.shop.service.ThingService;
import com.gzu.shop.vo.CategoryVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.expression.spel.ast.Literal;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Clown
 */
@Tag(name = "标签相关接口")
@Slf4j
@RestController
@RequestMapping("/category")
@AllArgsConstructor
public class CategoryController {
    private ClassificationFirstMapper classificationFirstMapper;
    private ClassificationSecondMapper classificationSecondMapper;
    private ThingMapper thingMapper;
    private ThingService thingService;

    @Operation(summary = "获取所有分类数据")
    @GetMapping("/getAllCategory")
    public Result<List<CategoryVO>> getAllCategory() {
//        System.out.println(classificationFirstMapper);
        // 获取所有classificationFirst数据
        List<ClassificationFirst> classificationFirsts = classificationFirstMapper.selectList(new QueryWrapper<>());
        log.info("classificationFirsts:{}", classificationFirsts);
        // 返回数据封装成列表
        ArrayList<CategoryVO> categoryVOS = new ArrayList<>();
        // 返回元素的子元素
        CategoryVO categoryVO = new CategoryVO();
        // 获取所有classificationSecond数据，并封装
        for (ClassificationFirst classificationFirst : classificationFirsts) {
            categoryVO.setClassificationFirst(classificationFirst);
            List<ClassificationSecond> classificationFirstId = classificationSecondMapper.selectList(new QueryWrapper<ClassificationSecond>().
                    eq("classification_first_id", classificationFirst.getId()));
            categoryVO.setClassificationSecondList(classificationFirstId);
            categoryVOS.add(categoryVO);
            // 必须new对象
            categoryVO = new CategoryVO();
        }
        return Result.success(ResultStatus.SUCCESS, categoryVOS);
    }

    @Operation(summary = "添加一级分类")
    @PostMapping("/first/add")
    public Result<Void> addFirst(@RequestBody ClassificationFirst entity) {

        // 空实体
        if (ObjectUtil.isEmpty(entity)) {
            throw new CategoryBusinessException(MessageConstant.DATA_IS_NULL);
        }

        // 判断标签名是否为空
        isEmptyTitle(entity.getTitle());

        // 查询一级标签
        ClassificationFirst classificationFirst = classificationFirstMapper.selectOne(new QueryWrapper<ClassificationFirst>()
                .eq("title", entity.getTitle()));
        // 如果存在名称相同
        if (classificationFirst != null) {
            throw new CategoryBusinessException(MessageConstant.SAME_CATEGORY_NAME);
        }
        // 更新分类
        classificationFirstMapper.insert(entity);

        return Result.success(ResultStatus.SUCCESS);
    }


    @Operation(summary = "添加二级分类")
    @PostMapping("/second/add")
    public Result<Void> addSecond(@RequestBody ClassificationSecond entity) {

        // 空实体
        if (ObjectUtil.isEmpty(entity)) {
            throw new CategoryBusinessException(MessageConstant.DATA_IS_NULL);
        }

        // 判断标签名是否为空
        isEmptyTitle(entity.getTitle());

        // 查询二级标签
        ClassificationSecond classificationSecond = classificationSecondMapper.selectOne(new QueryWrapper<ClassificationSecond>()
                .eq("title", entity.getTitle()));
        // 如果存在名称相同
        if (classificationSecond != null) {
            throw new CategoryBusinessException(MessageConstant.SAME_CATEGORY_NAME);
        }
        // 更新分类
        classificationSecondMapper.insert(entity);

        return Result.success(ResultStatus.SUCCESS);
    }


    @Operation(summary = "编辑一级分类")
    @PostMapping("/first/edit")
    public Result<Void> editFirst(@RequestBody ClassificationFirst entity) {
        // 空实体
        if (ObjectUtil.isEmpty(entity)) {
            throw new CategoryBusinessException(MessageConstant.DATA_IS_NULL);
        }

        // 判断标签名是否为空
        isEmptyTitle(entity.getTitle());

        // 查询一级标签
        ClassificationFirst classificationFirst = classificationFirstMapper.selectOne(new QueryWrapper<ClassificationFirst>()
                .eq("title", entity.getTitle()));
        // 如果存在名称相同
        if (classificationFirst != null) {
            throw new CategoryBusinessException(MessageConstant.SAME_CATEGORY_NAME);
        }
        // 更新分类
        classificationFirstMapper.updateById(entity);

        return Result.success(ResultStatus.SUCCESS);
    }


    @Operation(summary = "编辑二级分类")
    @PostMapping("/second/edit")
    public Result<Void> editSecond(@RequestBody ClassificationSecond entity) {
        // 空实体
        if (ObjectUtil.isEmpty(entity)) {
            throw new CategoryBusinessException(MessageConstant.DATA_IS_NULL);
        }

        // 判断标签名是否为空
        isEmptyTitle(entity.getTitle());

        // 查询二级标签
        ClassificationSecond classificationSecond = classificationSecondMapper.selectOne(new QueryWrapper<ClassificationSecond>()
                .eq("title", entity.getTitle()));
        // 如果存在名称相同
        if (classificationSecond != null) {
            throw new CategoryBusinessException(MessageConstant.SAME_CATEGORY_NAME);
        }
        // 更新分类
        classificationSecondMapper.updateById(entity);

        return Result.success(ResultStatus.SUCCESS);
    }


    @Operation(summary = "删除一级分类")
    @DeleteMapping("/first/del/{id}")
    @Transactional
    public Result<Void> deleteByFirstId(@PathVariable Long id) {
        // ID不存在
        if (id == null) {
            throw new CategoryBusinessException(MessageConstant.DATA_IS_NULL);
        }
        // 判断二级标签是否存在
        List<ClassificationSecond> classificationFirstId = classificationSecondMapper.selectList(new QueryWrapper<ClassificationSecond>()
                .eq("classification_first_id", id));
        if (!classificationFirstId.isEmpty()) {
            throw new CategoryBusinessException(MessageConstant.SECOND_CATEGORY_EXISTS);
        }
        // 没有二级分类，则删除类别
        classificationFirstMapper.deleteById(id);

        // 删除
        return Result.success(ResultStatus.SUCCESS);
    }

    @Operation(summary = "删除二级分类")
    @DeleteMapping("/second/del/{id}")
    @Transactional
    public Result<Void> deleteBySecondId(@PathVariable Long id) {
        // ID不存在
        if (id == null) {
            throw new CategoryBusinessException(MessageConstant.DATA_IS_NULL);
        }

        // 二级分类下是否还有商品
        List<Thing> classificationSecondId = thingMapper.selectList(new QueryWrapper<Thing>()
                .eq("classification_second_id", id));
        if (!classificationSecondId.isEmpty()) {
            throw new CategoryBusinessException(MessageConstant.THING_CATEGORY_EXISTS);
        }
        // 没有商品了，删除二级分类
        classificationSecondMapper.deleteById(id);

        // 删除
        return Result.success(ResultStatus.SUCCESS);
    }


    @Operation(summary = "判断标签名是否为空")
    private void isEmptyTitle(String title) {
        if (title == null || title.isEmpty()) {
            throw new CategoryBusinessException(MessageConstant.TITLE_EMPTY);
        }
    }


    @Operation(description = "根据种类实现分页查询")
    @PostMapping("/page/{startPage}/{pageSize}")
    public Result<IPage<Thing>> page(@PathVariable int startPage,
                                     @PathVariable int pageSize,
                                     @RequestBody(required = false) CategoryDTO categoryDTO) {
//        // 判断整体不为空
//        if (categoryDTO != null) {
//            // 商品查询条件
//            QueryWrapper<Thing> thingQueryWrapper = new QueryWrapper<>();
//            // 一级标签
//            List<ClassificationFirst> classificationFirsts = null;
//            // 一级标签id
//            List<Long> firstIds = new ArrayList<>();
//            // 二级标签id
//            List<Long> secondIds = new ArrayList<>();
//
//            HashSet<Long> firsts = new HashSet<>();
//            HashSet<Long> seconds = new HashSet<>();
//            // 一级标签不为空
//            if (categoryDTO.getClassificationFirstId() != null) {
//                QueryWrapper<ClassificationFirst> classificationFirstQueryWrapper = new QueryWrapper<>();
//                classificationFirstQueryWrapper.eq("id", categoryDTO.getClassificationFirstId());
//                classificationFirsts = classificationFirstMapper.selectList(classificationFirstQueryWrapper);
//
//                // 查询的一级标签
//                if (classificationFirsts != null && !classificationFirsts.isEmpty()) {
//                    for (ClassificationFirst classificationFirst : classificationFirsts) {
//                        firstIds.add(classificationFirst.getId());
//                    }
//                }
//            }
//
//            // 查询的二级标签不为空
//            if (categoryDTO.getClassificationSecondId() != null) {
//                QueryWrapper<ClassificationSecond> classificationSecondQueryWrapper = new QueryWrapper<ClassificationSecond>().eq("id"
//                        , categoryDTO.getClassificationSecondId());
//                classificationSecondQueryWrapper.eq("id", categoryDTO.getClassificationSecondId());
//                List<ClassificationSecond> classificationSeconds = classificationSecondMapper.selectList(classificationSecondQueryWrapper);
//
//
//                secondIds = new ArrayList<>();
//                for (ClassificationSecond classificationSecond : classificationSeconds) {
//                    secondIds.add(classificationSecond.getId());
//                }
//
//                // 求二级标签和一级标签的集合
//                firsts = new HashSet<>(firstIds);
//                seconds = new HashSet<>(secondIds);
//
//                seconds.retainAll(firsts);
//
//            }
//
//            if (categoryDTO.getTitle() != null && !categoryDTO.getTitle().isEmpty()) {
//                QueryWrapper<Thing> title = thingQueryWrapper.like("title", categoryDTO.getTitle());
//                List<Thing> things = thingMapper.selectList(title);
//
//                log.info("thing:{}", things);
//
//                for (Long id : seconds) {
//                    List<Thing> collect = things.stream()
//                            .filter(item -> !Objects.equals(item.getClassificationSecondId(), id))
//                            .toList();
//                    log.info("collect:{}", collect);
//
//                }

//        log.info("mapper:{}", thingMapper.getThingsByCategory(categoryDTO));


//            }
//            return Result.success(ResultStatus.SUCCESS, thingService.page(Page.of(startPage, pageSize), thingQueryWrapper));
//        }
//        return Result.success(ResultStatus.SUCCESS, thingService.page(Page.of(startPage, pageSize)));
//    }
        return Result.success(ResultStatus.SUCCESS, thingMapper.getThingsByCategory(new Page<>(startPage, pageSize), categoryDTO));
    }
}
